package com.snail.app;

import com.snail.app.config.entity.DbConfigDatabase;
import com.snail.app.config.entity.DbDicDatabase;
import com.snail.app.config.service.DbConfigDatabaseService;
import com.snail.app.config.service.DbDicDatabaseService;
import com.snail.common.toolUtil.jdbc.JdbcUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description
 * @date 2021/8/9
 * @autor houyanfeng
 */
@Component
public class DbOperationUtil {
    @Autowired
    private DbConfigDatabaseService configDBService;
    @Autowired
    private DbDicDatabaseService dicDatabaseService;

    public Map<String, Object> queryMap(String databaseKey, String sql) throws Exception {
        Map<String, Object> params = new HashMap<>();
        DbConfigDatabase dbconfig = configDBService.getById(databaseKey);
        DbDicDatabase dicDatabase = dicDatabaseService.get(dbconfig.getType(), dbconfig.getVersion());
        Map<String, Object> result = JdbcUtil.queryMap(dicDatabase.getDriver(), dbconfig.getUrl(), dbconfig.getAccount(), dbconfig.getPassword(), sql);
        return result;
    }

    /**
     * 在指定库中执行sql
     *
     * @param databaseKey 数据库标识keyword
     * @param sql         原生sql
     * @return List<Map < String, Object>>
     * @throws Exception
     */
    public List<Map<String, Object>> queryListMap(String databaseKey, String sql) throws Exception{
        DbConfigDatabase dbconfig = configDBService.getById(databaseKey);
        DbDicDatabase dicDatabase = dicDatabaseService.get(dbconfig.getType(), dbconfig.getVersion());
        List<Map<String, Object>> result = JdbcUtil.queryListMap(dicDatabase.getDriver(), dbconfig.getUrl(), dbconfig.getAccount(), dbconfig.getPassword(), sql);
        return result;
    }

    public List<Object> queryListSingle(String databaseKey, String sql) throws Exception {
        DbConfigDatabase dbconfig = configDBService.getById(databaseKey);
        DbDicDatabase dicDatabase = dicDatabaseService.get(dbconfig.getType(), dbconfig.getVersion());
        List<Object> result = JdbcUtil.queryListString(dicDatabase.getDriver(), dbconfig.getUrl(), dbconfig.getAccount(), dbconfig.getPassword(), sql);
        return result;
    }

    public void execDel(String databaseKey, String sql) throws Exception {
        DbConfigDatabase dbconfig = configDBService.getById(databaseKey);
        DbDicDatabase dicDatabase = dicDatabaseService.get(dbconfig.getType(), dbconfig.getVersion());
        JdbcUtil.executeUpdate(dicDatabase.getDriver(), dbconfig.getUrl(), dbconfig.getAccount(), dbconfig.getPassword(), sql);
    }

}
